package fun.ty13;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.constants.ZuulConstants;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 桃缘十三
 * @date 2022/11/29 11:50
 */
public class LoginFilter extends ZuulFilter {

    /**
     * 过滤器类型
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤器的执行顺序，数字越小，优先级越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 1;
    }

    /**
     * 返回true表示过滤器生效，执行run方法
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //1.获取当前请求的url
        String uri = RequestContext.getCurrentContext().getRequest().getRequestURI();
        //2. 判断是否放行
        if (uri.endsWith("/login") || uri.endsWith("/register") || uri.contains("/static/")) {
            return false;
        }

        return true;
    }

    /**
     * 过滤器的具体业务逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        // 1.获取请求头
        String token = RequestContext.getCurrentContext().getRequest().getHeader("token");
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        // 2.判断是否登录
        if (token == null || "".equals(token)) {
            // 3.未登录，拦截
            response.setContentType("text/html;charset=utf-8");
            try {
                response.getWriter().println("{\"success\":false,\"msg\":\"timeout\"}");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            // 4.设置不转发
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        return null;
    }
}
